package com.xxxx.server.config;

import com.xxxx.server.utils.JwtTokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class JwtAuthencationTokenFilter extends OncePerRequestFilter {
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private JwtTokenUtils jwtTokenUtils;
    @Autowired
    private UserDetailsService userDetailsService;
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String authHeader=httpServletRequest.getHeader(tokenHeader);
        if (null!=authHeader&&authHeader.startsWith(tokenHead)){
            String token = authHeader.substring(tokenHead.length());
            String username = jwtTokenUtils.getUserNameToken(token);
            if (username!=null&& null== SecurityContextHolder.getContext().getAuthentication()){
                UserDetails userDetails =userDetailsService.loadUserByUsername(username);
                if (jwtTokenUtils.validateToken(token,userDetails)){
                    SecurityContextHolder.getContext().setAuthentication
             (new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities()));
                }
            }
        }
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }
}
